import { BASE_URL } from "../contants/constants.js";
import {clearToken, msgConfirm, msgTip} from "../util/util.js";

export default class SseService {
    constructor(url) {
        this.baseUrl = BASE_URL;
        this.endpoint = url;
        this.abortController = null;
        this.callbacks = {};
    }

    async connect(prompt, callbacks = {}) {
        this.disconnect();
        const url = `${this.baseUrl}${this.endpoint}?prompt=${encodeURIComponent(prompt)}`;
        this.callbacks = callbacks;
        this.abortController = new AbortController();

        try {
            // 手动添加拦截器逻辑
            const tokenName = sessionStorage.getItem('tokenName');
            const tokenValue = sessionStorage.getItem('tokenValue');
            const headers = {};
            if (tokenName && tokenValue) {
                headers[tokenName] = tokenValue;
            }

            const response = await fetch(url, {
                method: 'GET',
                headers: headers,
                signal: this.abortController.signal
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            this.callbacks.onConnect?.();
            await this.processStream(response);
        } catch (error) {
            this.callbacks.onError?.(error);
            this.disconnect();
        }
    }

    async processStream(response) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let isStreaming = true;

        const processChunk = async ({ done, value }) => {
            if (done || !isStreaming) {
                isStreaming = false;
                // 处理最后的数据片段
                if (buffer.trim()) this.parseSSEEvent(buffer);
                this.callbacks.onComplete?.();
                this.disconnect();
                return;
            }

            buffer += decoder.decode(value, { stream: true });

            // 完整事件分割逻辑
            while (true) {
                const eventEndIndex = buffer.indexOf('\n\n');
                if (eventEndIndex === -1) break;

                const eventData = buffer.slice(0, eventEndIndex);
                buffer = buffer.slice(eventEndIndex + 2);

                if (eventData) this.parseSSEEvent(eventData);
            }

            return reader.read().then(processChunk);
        };

        reader.read().then(processChunk);
    }

    parseSSEEvent(rawEvent) {
        try {
            let eventType = 'message';
            let data = '';

            rawEvent.split('\n').forEach(line => {
                if (line.startsWith('event:')) {
                    eventType = line.replace('event:', '').trim();
                } else if (line.startsWith('data:')) {
                    data += line.replace('data:', '').trim();
                }
            });

            if (data) {
                const parsedData = JSON.parse(data);
                if (eventType === 'done') {
                    this.callbacks.onComplete?.(parsedData);
                } else {
                    this.callbacks.onData?.(parsedData);
                }
            }
        } catch (e) {
            this.callbacks.onError?.(e);
        }
    }

    disconnect() {
        if (this.abortController) {
            // 延迟清理确保数据完整性
            setTimeout(() => {
                this.abortController.abort();
                this.abortController = null;
                this.callbacks = {};
            }, 100);
        }
    }
}
